/**
 * Copyright (C) 2012 Oleg Anastassov <o.anastasov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.ent.desktop.ui.util.comparator;

import java.util.Comparator;

/**
 * @author Oleg Anastassov
 */
public class BooleanComparator<T> implements Comparator<T> {

    /**
     * Column index in array of objects for compare.
     */
    private int columnIndex = -1;

    /**
     * Sort mode (if 1 - ascending, if -1 - descending).
     */
    private short ascending = 1;

    /**
     * Creates a new <code>BooleanComparator</code>.
     *
     * @param columnIndex column index
     */
    public BooleanComparator(int columnIndex) {
        super();
        this.columnIndex = columnIndex;
    }

    /**
     * Creates a new <code>BooleanComparator</code>.
     *
     * @param columnIndex column index
     * @param ascending   sort mode (if true - ascending, otherwise - descending)
     */
    public BooleanComparator(int columnIndex, boolean ascending) {
        this(columnIndex);
        if (!ascending) {
            this.ascending = -1;
        }
    }

    /**
     * Compares value in rows by determinate column index.
     *
     * @param row1 first array of objects
     * @param row2 second array of objects
     * @return result of compare
     */
    public int compare(T row1, T row2) {
        Boolean value1 = null;
        Boolean value2 = null;
        if (row1 instanceof Object[] && row2 instanceof Object[]) {
            value1 = (Boolean) ((Object[]) row1)[columnIndex];
            value2 = (Boolean) ((Object[]) row2)[columnIndex];
        }

        if (value1 != null) {
            if (value2 != null) {
                return value1.compareTo(value2) * ascending;
            } else {
                return ascending;
            }
        } else {
            if (value2 != null) {
                return -ascending;
            } else {
                return 0;
            }
        }
    }
}
